<template>
	<view class="content">
		<view class="gradient-bg">
			<!-- 渐变背景 -->
			<view class="list-card-wrap">
				<view class="flex-row-between" style="margin-bottom: 8rpx;">
					<view class="flex-row">
						<text class="white-text font-24">任务编号</text>
						<text class="white-text font-24" style="margin-left: 20rpx;">{{taskInfo.no}}</text>
					</view>
					<view class="tag tag-gray">{{taskInfo.storehouseLocationNo}}</view>
				</view>
				<view class="list-card">
					<view class="">
						<text class="black-text-34">{{taskInfo.productName}}</text>
						<text class="gray-text font-30">({{taskInfo.productNo}})</text>
					</view>
					<view class="content-blue flex-row">
						<view class="flex-column flex1">
							<text class="gray-text">总数量</text>
							<text class="black-text">{{taskInfo.totalQuantity}}</text>
						</view>
						<view class="split"></view>
						<view class="flex-column flex1">
							<text class="gray-text">抽检数量</text>
							<text class="black-text">{{taskInfo.quantity}}</text>
						</view>
						<view class="split"></view>
						<view class="flex-column flex1">
							<text class="gray-text">已检数量</text>
							<text class="blue-text">{{taskInfo.inspectedQuantity}}</text>
						</view>
					</view>
				</view>
			</view>
			
			<view class="s-input-wrap">

				<view class="s-input-box flex-row">
					<text class="black-text">条码</text>
					<input v-model="barcode" class="s-input flex1" placeholder="扫描 / 输入条码" @confirm="inputCode"/>
					<image v-if="barcode" class="s-input-icon clear-icon" src="/static/images/clear.png" @click="clearBarcode"></image>
					<image class="s-input-icon" src="/static/images/scan.png"></image>
				</view>
			</view>
		</view>
		
		<scroll-view class="content-list-card" scroll-y style="height: calc(100vh - 595rpx);">
			<view v-for="(barcodeItem,index) in taskDetailBarcode" :key="index" >
				<view style="margin: 16rpx 0;">
					<text class="gray-text">条码</text>
					<text class="black-text-34" style="margin-left: 8rpx;">{{barcodeItem }}</text>
					<text style="margin-left: 10px;" class="gray-text">数量</text>
					<text class="black-text-34" style="margin-left: 8rpx;">{{taskDetailGroupByBarcode[barcodeItem][0].barcodeQty}}</text>
				</view>
				<view class="card" v-for="(item,itemIndex) in taskDetailGroupByBarcode[barcodeItem]" :key="itemIndex" >
					<view class="title">
							<text class="gray-text">质检项目</text>
							<text class="black-text-34" style="margin-left: 8rpx;">{{item.itemName}}</text>
					</view>
					<view class="">
						<view v-if="item.valueType == 'RANGE'" class="flex-row split">
							<view class="content flex-column" style="width:50%">
								<text class="gray-text">标准上限</text>
								<text class="black-text-34">{{item.upperLimitValue}}</text>
							</view>
							<view class="content flex-column" style="width:50%">
								<text class="gray-text">标准下限</text>
								<text class="black-text-34">{{item.lowerLimitValue}}</text>
							</view>
						</view>
						<view class="flex-row">
							<view class="content flex-column" style="width:50%">
								<view class="flex-row">
									<text class="gray-text">实际值</text>
								</view>
								<view class="flex-row content-input ">
									<input v-if="item.valueType == 'RANGE'" @input="inputActualVAlue($event,barcodeItem,itemIndex)" v-model="item.actualValue" type="digit" class="blue-text font-34 flex1" placeholder="" ></input>
									<picker class="flex1 flex-row" v-if="item.valueType == 'STATUS'"  @change="(arr)=>inputActualVAlue(arr,barcodeItem,itemIndex)" :value="item.actualValue" :range="actualList">
										<view class="blue-text font-34 flex1" style="text-align: center;height: 50rpx;">{{item.actualValue?item.actualValue:'请选择实际值'}}</view>
									</picker>
									<image class="edit-icon" src="/static/images/edit.png"></image>
									<!-- <uni-icons class="flex1" type="compose" size="18" color="#458B9C"></uni-icons> -->
								</view>
							</view>
							<view class="content flex-column" style="width:50%">
								<text class="gray-text">结果</text>
								<text :class="item.qualityResult == 'OK'?'q-tag':'q-tag q-tag-red'">{{item.qualityResult}}</text>
								<!-- <text class="q-tag q-tag-red">NG</text> -->
							</view>
						</view>
					</view>
				</view>
			</view>
		</scroll-view>
		
		<view class="content-list-total flex-row-end">
			<view class="flex-row">
				<view class="botton" @click="saveQualityItem">确认</view>
				<view class="botton p-botton"  @click="finishTask">完成</view>
			</view>
		</view>
		
		<popup ref="inputDialog" @beforeClosed="" @handleCheck="finishTaskHasProcessMode">
			<view class="">
				<view class="flex-row-start"><text class="gray-text font-30" style="width:150rpx">检验结果：</text><text class="q-tag q-tag-red font-34">NG</text></view>
				<view class="flex-row-start" style="margin-top: 16rpx;">
					<text class="gray-text font-30" style="width:150rpx">处理方式：</text>
					<picker @change="(arr)=>bindPickerActualValue(arr,item)" :value="processMode.value" :range="processModeList" range-key="label">
						<view class="black-text font-34" style="height:50rpx">{{processMode&&processMode.label?processMode.label:'请选择处理方式'}}</view>
					</picker>
				</view>
				<view v-if="processMode.value == '2'" class="flex-row-start" style="margin-top: 16rpx;">
					<text class="gray-text font-30" style="width:150rpx">退货数量：</text>
					<input type="number" v-model="returnQuantity" @input="setNum" class="black-text font-34 flex1" placeholder="请输入退货数量" />
				</view>
			</view>
		</popup>
			
	</view>
</template>

<script>
	import { validNum } from "@/utils/common"
	import {
		getTaskInfoById,
		getTaskDetail,
		getQualityItemList,
		saveDetailData,
		getTaskNgNum,
		completeTask,
		getInfoByBarcode
	} from "./api"
	export default {
		onLoad(option) {
			this.taskId = option.id;
		  },
		  created() {
		  		this.getTaskDetail();
		  },
		data(){
			return{
				taskId:'',
				barcode:'',
				taskInfo:{},
				// 详情根据物料条码分组的对象
				taskDetailGroupByBarcode:{},
				taskDetailBarcode:[],
				qualityItem:[],
				actualList:["OK","NG"],
				processModeList:[
					{
						value:'1',
						label:'让步接收'
					},
					{
						value:'2',
						label:'部分接收'
					},
					{
						value:'3',
						label:'退货'
					}],
				processMode:{
					value:'1',
					label:'让步接收'
				},
				returnQuantity:''
			}
		},
		methods: {
			setNum(e){
				this.$set(this,'returnQuantity',validNum(e))
			},
			bindPickerActualValue(e){
				this.processMode = this.processModeList[e.detail.value]
			},
			getTaskDetail(){
				// 清空原始数据
				this.$set(this,'taskDetailGroupByBarcode',{});
				this.$set(this,'taskDetailBarcode',[]);
				this.$set(this,'qualityItem',[]);
				getTaskInfoById(this.taskId).then(res => {
					if (res.code == 200) {
						this.taskInfo = res.data
						// 查询质检任务对应的物料质检项
						getQualityItemList({
							productNo:this.taskInfo.productNo
						}).then(res => {
							if (res.code == 200) {
								this.qualityItem = res.rows;
							} else {
								res.msg && this.$modal.confirmClose(res.msg)
							}
						})
						// 继续查询质检任务明细项
						getTaskDetail({
							taskNo:this.taskInfo.no,
							pageNum:1,
							pageSize:99999
						}).then(res => {
							if (res.code == 200 && res.rows.length > 0) {
								res.rows.forEach((item) => {
									let barcode = item.barcode;
									if(this.taskDetailGroupByBarcode[barcode] && this.taskDetailGroupByBarcode[barcode].length > 0){
										// 如果已经存在，则在该对象下新增
										this.taskDetailGroupByBarcode[barcode].push(item);
									}else{
										let detailList = [];
										detailList.push(item);
										this.taskDetailBarcode.push(item.barcode);
										this.$set(this.taskDetailGroupByBarcode,barcode,detailList);
									}
								});
							} else if (res.code !== 200) {
								res.msg && this.$modal.confirmClose(res.msg)
							}
						})
					} else {
						res.msg && this.$modal.confirmClose(res.msg)
					}
				})
			},
			// 扫描、输入条码
			inputCode(){
				if(!this.barcode){
					return;
				}
				// 判断和原有条码是否重复
				if(this.taskDetailGroupByBarcode[this.barcode] && this.taskDetailGroupByBarcode[this.barcode].length > 0){
					this.$modal.msgError("条码存在重复");
					return;
				}
				// 需要判断条码是否存在
				getInfoByBarcode(this.barcode).then(res => {
					if (res.code == 200 && res.data) {
						// 判断条码和质检任务的是否一致
						if(res.data.productNo != this.taskInfo.productNo){
							this.$modal.msgError("输入的条码物料与质检任务不一致");
							return;
						}
						this.taskDetailBarcode.splice(0,0,this.barcode);
						let detailList = [];
						let qualityItem = JSON.parse(JSON.stringify(this.qualityItem))
						qualityItem.forEach((item) => {
							item.id = null;
							item.no = null;
							item.barcode = this.barcode;
							item.taskNo = this.taskInfo.no;
							item.barcodeQty = res.data.qty;
							detailList.push(item);
						});
						this.$set(this.taskDetailGroupByBarcode,this.barcode,detailList);
						this.$set(this,'barcode','');
					} else {
						if (res.code !== 200) {
							res.msg && this.$modal.confirmClose(res.msg)
						} else {
							this.$modal.msgError("输入的条码有误");
						}
						return;
					}
				})
				
			},
			inputActualVAlue(val,barcode,itemIndex){
				let taskItem = this.taskDetailGroupByBarcode[barcode][itemIndex];
				if(taskItem.valueType == 'RANGE'){
					let inputNum = parseFloat(val.detail.value);
					if(parseFloat(taskItem.upperLimitValue) >= inputNum && 
					parseFloat(taskItem.lowerLimitValue) <= inputNum){
						taskItem.qualityResult = 'OK';
					}else{
						taskItem.qualityResult = 'NG';
					}
					
				}
				if(taskItem.valueType == 'STATUS'){
					taskItem.actualValue = this.actualList[val.detail.value];
					taskItem.qualityResult = taskItem.actualValue;
				}
				this.$set(this.taskDetailGroupByBarcode[barcode],itemIndex,taskItem)
			},
			saveQualityItem(){
				// 数据需要转换后提交
				let saveData = [];
				this.taskDetailBarcode.forEach((item) => {
					saveData = saveData.concat(this.taskDetailGroupByBarcode[item]);
				});
				let isAllInput = true;
				// 判断是否所有项目都有填实际值
				saveData.forEach((item) => {
					if(!item.actualValue){
						isAllInput = false;
						this.$modal.msgError("条码[" + item.barcode + "]的质检项目[" + item.itemName + "]实际值不能为空" );
						return;
					}
				});
				if(isAllInput){
					this.$modal.confirm('是否确认提交').then(() => {
						saveDetailData(saveData).then(res => {
							if (res.code == 200) {
								// 刷新列表
								this.$modal.msgSuccess("操作成功");
								this.getTaskDetail();
							} else {
								res.msg && this.$modal.confirmClose(res.msg)
							}
						})
					})
				}
			},
			// 完成任务
			finishTask(){
				if(!this.taskDetailBarcode || this.taskDetailBarcode.length == 0){
					this.$modal.msgError('请保存质检明细');
					return;
				}
				this.$modal.confirm('是否确认完成任务').then(() => {
					// 需要先将数据保存
					let saveData = [];
					this.taskDetailBarcode.forEach((item) => {
						saveData = saveData.concat(this.taskDetailGroupByBarcode[item]);
					});
					let isAllInput = true;
					// 判断是否所有项目都有填实际值
					saveData.forEach((item) => {
						if(!item.actualValue){
							isAllInput = false;
							this.$modal.msgError("条码[" + item.barcode + "]的质检项目[" + item.itemName + "]实际值不能为空" );
							return;
						}
					});
					this.$modal.loading("加载中...")
					if(isAllInput){
						saveDetailData(saveData).then(res => {
							if (res.code == 200) {
								// 保存成功后，调用接口判断是否全部质检明细都为合格
								getTaskNgNum({
									taskNo:this.taskInfo.no
								}).then(resNgNum => {
									this.$modal.closeLoading()
									
									if (resNgNum.code == 200) {
										// 如果不合格质检项数量大于0，需要弹窗选择处理方式
										if(resNgNum.data > 0){
											this.$refs.inputDialog.open()
										}
										// 如果全部合格，调用接口完成质检任务
										else{
											this.$modal.loading("加载中...")
											completeTask({
												id:this.taskInfo.id,
												qualityResult:"OK"
											}).then(completeRes => {
												this.$modal.closeLoading()
												if(completeRes.code == 200){
													// 跳转到列表页并刷新数据
													this.$modal.msgSuccess("操作成功");
													// 延迟1秒跳转
													uni.$emit('refreshList',{msg:'页面更新'})
													setTimeout(()=>{
														uni.navigateBack();
													}, 1000);
												} else {
													res.msg && this.$modal.confirmClose(res.msg)
												}
											})
										}
									} else {
										resNgNum.msg && this.$modal.confirmClose(resNgNum.msg)
									}
								})
							} else {
								this.$modal.closeLoading()
								res.msg && this.$modal.confirmClose(res.msg)
							}
						})
					}
					
				})
			},
			// 完成任务（弹窗后确认，带处理方式）
			finishTaskHasProcessMode(){
				if(this.processMode.value == '2'){
					if(!this.returnQuantity){
						this.$modal.msg("请输入退货数量");
						return
					}
					if(this.returnQuantity > this.taskInfo.totalQuantity){
						this.$modal.msg("退货数量不能大于检测数量");
						return
					}
				}
				completeTask({
					id:this.taskInfo.id,
					qualityResult:"NG",
					processMode:this.processMode.value,
					returnQuantity:this.returnQuantity
				}).then(completeRes => {
					if(completeRes.code == 200){
						// 跳转到列表页并刷新数据
						this.$refs.inputDialog.closed()
						this.$modal.msgSuccess("操作成功");
						// 延迟1秒跳转
						uni.$emit('refreshList',{msg:'页面更新'})
						setTimeout(()=>{
							uni.navigateBack();
						}, 1000);
					}else{
						this.$modal.msgError(completeRes.msg);
					}
				})
			},
			clearBarcode() {
				this.$set(this, 'barcode', '');
			}
		}
	}
</script>

<style>
	page{
		background-color: #F8F8F8;
	}
</style>
<style scoped>
	
</style>